package com.huawei.demo;

import com.huaweicloud.sdk.ccm.v1.CcmClient;
import com.huaweicloud.sdk.ccm.v1.model.CreateCertificateAuthorityObsAgencyRequest;
import com.huaweicloud.sdk.ccm.v1.model.CreateCertificateAuthorityObsAgencyResponse;
import com.huaweicloud.sdk.ccm.v1.model.ShowCertificateAuthorityObsAgencyRequest;
import com.huaweicloud.sdk.ccm.v1.model.ShowCertificateAuthorityObsAgencyResponse;
import com.huaweicloud.sdk.ccm.v1.region.CcmRegion;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;

public class CrlManagerDemo {

    public static void main(String[] args) {

        /*
         * 基础认证信息：
         * - ak: 华为云账号Access Key
         * - sk: 华为云账号Secret Access Key
         * - domainId: 华为云账号ID 详情见https://support.huaweicloud.com/productdesc-iam/iam_01_0023.html
         * - ccmEndpoint: 华为云CCM服务(PCA属于CCM下的微服务)的访问终端地址
         */
        String ak = "<AccessKey>";
        String sk = "<SecretAccessKey>";
        String domainId = "<DomainID>";
        String ccmEndpoint = "<CcmEndpoint>";

        // 1.准备访问华为云的认证信息，PCA为全局服务
        final GlobalCredentials auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk)
                .withDomainId(domainId);

        // 2.初始化SDK，传入认证信息及CCM服务的访问终端地址
        final CcmClient ccmClient = CcmClient.newBuilder()
                .withCredential(auth)
                .withRegion(CcmRegion.CN_NORTH_4)
                .withEndpoint(ccmEndpoint).build();

        // 3.查询当前帐号是否已给CCM服务授予OBS的委托
        boolean isHaveAgency = checkObsAgency(ccmClient);

        // 4.当前帐号未给CCM服务授予OBS的委托时，可选择创建（当前帐号需要具备安全管理员权限）
        // 若已授权，发起创建授权的请求也不会重复创建授权
        if(!isHaveAgency) {
            String agencyId = createObsAgency(ccmClient);
            System.out.println(agencyId);
        }
    }

    private static boolean checkObsAgency(CcmClient ccmClient) {
        ShowCertificateAuthorityObsAgencyResponse response;
        ShowCertificateAuthorityObsAgencyRequest request = new ShowCertificateAuthorityObsAgencyRequest();
        try {
            response = ccmClient.showCertificateAuthorityObsAgency(request);
        } catch (Exception e) {
            System.out.println("error info: " + e.getMessage());
            return false;
        }
        return "true".equalsIgnoreCase(response.getAgencyGranted());
    }

    private static String createObsAgency(CcmClient ccmClient) {
        CreateCertificateAuthorityObsAgencyResponse response;
        CreateCertificateAuthorityObsAgencyRequest request = new CreateCertificateAuthorityObsAgencyRequest();
        try {
            response = ccmClient.createCertificateAuthorityObsAgency(request);
        } catch (Exception e) {
            System.out.println("error info: " + e.getMessage());
            return null;
        }
        return response.getAgencyId();
    }
}
